<?php

class Admin_LoginController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
        $this->_helper->layout->setLayout('adminlogin');
    }

    public function indexAction() {
        $adminValidation = new Validations_User();
        $valid = $adminValidation->hasidentity();
        if ($valid) {
            if ($adminValidation->getUserTypeId() == 1) {
                $this->_redirect('/admin/index');
            }else{                
                $this->view->message = "You are not admin.";
            }
        }

        $form = new Admin_Form_Login();
        $this->view->form = $form;

        /**
         * - Check for valid input
         * - Authenticate using adapter
         * - Persist user record to session
         * - Redirect to original requirest URL if present
         */
        $valid = false;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $email = $values['email'];
                $password = md5($values['password']);
                $valid = true;
            }
        }

        if ($valid) {
            $authAdapter = $this->getAuthAction();
            $authAdapter->setIdentity($email)
                    ->setCredential($password);
            $auth = Zend_Auth::getInstance();
            $result = $auth->authenticate($authAdapter);
            if ($result->isValid()) {
                $identity = $authAdapter->getResultRowObject();
                $authStorage = $auth->getStorage();
                $authStorage->write($identity);
                $this->_redirect('/admin/index');
            } else {
                $this->view->message = "Username or Password Invalid";
            }
        }
    }

    public function getAuthAction() {
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $authAdapter->setTableName('users')
                ->setIdentityColumn('email')
                ->setCredentialColumn('password');
        return $authAdapter;
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/admin/login');
    }

}

